import {Component, OnInit, ViewChild} from '@angular/core';
import {NgForm} from '@angular/forms';

@Component({
  selector: 'app-template-driven01',
  templateUrl: './template-driven01.component.html',
  styleUrls: ['./template-driven01.component.less']
})
export class TemplateDriven01Component implements OnInit {

  person: Person = new Person();
  @ViewChild('form') form: NgForm;
  validationMessage: PersonValidationMessage = new PersonValidationMessage();
  formErrors = {
    name: null,
    age: null,
    mail: null,
    mobile: null,
    phone: null,
    salary: null,
    address: null,
    gender: null
  };

  constructor() { }

  ngOnInit() {
    this.form.valueChanges.subscribe(data => this.onValueChanged(data));
  }

  onValueChanged(data) {
    for ( const field of Object.keys(this.validationMessage)) {
      this.formErrors[field] = '';
      const  ctrl = this.form.form.get(field);
      if (!!ctrl && ctrl.dirty && !ctrl.valid) {
        console.log(ctrl.errors);
        for (const errorKey of Object.keys(ctrl.errors)) {
          this.formErrors[field] += this.validationMessage[field][errorKey];
        }
      }
    }
  }

}

export class Person {
  name: string;
  age: string;
  mail: string;
  mobile: string;
  phone: string;
  salary: number;
  address: string;
  gender: Gender = new Gender();
}
export class Gender {
  male: boolean;
  female: boolean;
}
export class PersonValidationMessage{
  name = {
    minlength: '至少2个字符。',
    errorMsg: '中文及中文字符最多15个，英文及英文字符最多30个。'
  };

  age = {
    errorMsg: '只能输入整数，且最多三位。'
  };

  mail = {
    errorMsg: '邮箱格式有误。'
  };

  mobile = {
    errorMsg: '手机号格式有误。'
  };

  phone = {
    errorMsg: '办公电话格式有误。'
  };

  salary = {
    errorMsg: '最多允许输入6位数字，其中最多2位小数！'
  };

  address = {
    errorMsg: '地址最多输入50个汉字，或100个英文！'
  };
}
